<template>
  <div class="app-container">
    <!-- 页面标题 -->
    <div class="mb-6">
      <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-gray-800 mb-2">
        课程调整申请
      </h2>
      <p class="text-gray-500">
        教师因临时有事或外出学习等情况，可在此提交课程调整申请
      </p>
    </div>

    <!-- 课程选择区域 -->
    <el-card shadow="hover" class="mb-6 transition-all duration-300 hover:shadow-md">
      <h3 class="text-lg font-semibold text-gray-800 mb-4 flex items-center">
        <i class="el-icon-schedule mr-2 text-primary"></i>选择需要调整的课程
      </h3>

      <!-- 搜索和筛选 -->
      <div class="flex flex-col md:flex-row md:items-center justify-between mb-6 gap-4 p-2 bg-gray-50 rounded-lg">
        <div class="relative flex-grow max-w-md">
          <el-input
              placeholder="搜索课程名称、课程代码..."
              prefix-icon="Search"
              class="w-full"
              v-model="searchKeyword"
              @input="handleSearch"
          ></el-input>
        </div>
        <div class="flex flex-wrap gap-3">
          <el-select placeholder="全部学期" class="min-w-[140px]" v-model="selectedSemester" @change="handleFilterChange">
            <el-option label="2023-2024学年 第一学期" value="2023-1"></el-option>
            <el-option label="2023-2024学年 第二学期" value="2023-2"></el-option>
            <el-option label="2024-2025学年 第一学期" value="2024-1"></el-option>
            <el-option label="2024-2025学年 第二学期" value="2024-2"></el-option>
            <el-option label="2025-2026学年 第一学期" value="2025-1"></el-option>
            <el-option label="2025-2026学年 第二学期" value="2025-2"></el-option>
          </el-select>
        </div>
      </div>

      <!-- 课程列表 -->
      <el-table
          :data="filteredCourseList"
          border
          stripe
          :header-cell-style="{background: '#f5f7fa'}"
          class="mb-4 transition-all duration-300"
          v-loading="tableLoading"
          element-loading-text="加载中..."
      >
        <el-table-column type="selection" width="55"></el-table-column>

        <el-table-column label="课程信息" min-width="220">
          <template #default="scope">
            <div class="flex items-center">
              <div class="w-10 h-10 rounded bg-primary/10 flex items-center justify-center text-primary mr-3">
                <i class="el-icon-book"></i>
              </div>
              <div>
                <p class="font-medium">{{ scope.row.courseName }}</p>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="班级名称" prop="className" min-width="180"></el-table-column>

        <el-table-column label="学年学期" min-width="160">
          <template #default="scope">
            <div>
              <p>{{ scope.row.academicYear }}</p>
              <p class="text-sm text-gray-500">{{ scope.row.semesterText }}</p>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="上课时间" min-width="180">
          <template #default="scope">
            <div>
              <p>
                <span class="inline-block w-16">{{ getWeekDay(scope.row.weekDay) }}</span>
                <span>{{ scope.row.startTime }}-{{ scope.row.endTime }}</span>
              </p>
              <p class="text-sm text-gray-500">
                {{ scope.row.weekType === 2 ? '单周' : scope.row.weekType === 4 ? '双周' : '每周' }}
              </p>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="上课教室" prop="classroom" min-width="140"></el-table-column>

        <el-table-column label="选课情况" min-width="160">
          <template #default="scope">
            <div>
              <p>
                {{ scope.row.currentEnrollment }}/{{ scope.row.maxCapacity }}人
              </p>
              <div class="flex items-center">
                <el-progress
                    :percentage="scope.row.enrollmentRate"
                    :stroke-width="6"
                    :show-text="false"
                    class="w-24 mt-1"
                ></el-progress>
                <span class="text-xs text-gray-500 ml-2">{{ scope.row.enrollmentRate }}%</span>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="学院" prop="department" min-width="140"></el-table-column>

        <el-table-column label="状态" min-width="100">
          <template #default="scope">
            <el-tag
                :type="scope.row.status === 1 ? 'success' : 'warning'"
                :disable-transitions="false"
            >
              {{ scope.row.status === 1 ? '正常' : '已调整' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" min-width="140">
          <template #default="scope">
            <el-button
                link
                type="primary"
                @click="selectCourse(scope.row)"
                class="mr-2 hover:text-primary/80 transition-colors"
            >
              选择
            </el-button>
            <el-button
                link
                type="info"
                @click="showCourseDetail(scope.row)"
                class="hover:text-gray-700 transition-colors"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 无数据状态 -->
      <div v-if="!tableLoading && filteredCourseList.length === 0" class="text-center py-8">
        <el-empty description="未找到匹配的课程数据"></el-empty>
      </div>

      <!-- 分页 -->
      <div class="flex items-center justify-between mt-6" v-if="filteredCourseList.length > 0">
        <div class="text-sm text-gray-500">显示 {{ (currentPage-1)*pageSize + 1 }}-{{ Math.min(currentPage*pageSize, total) }} 条，共 {{ total }} 条</div>
        <el-pagination
            v-model:current-page="currentPage"
            :page-size="pageSize"
            :page-sizes="[5, 10, 20]"
            :total="total"
            layout="prev, pager, next, jumper, sizes"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 历史调课记录区域 -->
    <el-card shadow="hover" class="transition-all duration-300 hover:shadow-md">
      <h3 class="text-lg font-semibold text-gray-800 mb-4 flex items-center">
        <i class="el-icon-document mr-2 text-primary"></i>课程调整申请记录
      </h3>

      <!-- 加载状态 -->
      <div v-if="historyLoading" class="text-center py-8">
        <div class="flex flex-col items-center">
          <el-icon class="is-loading" size="24">
            <Loading />
          </el-icon>
          <p class="mt-2 text-gray-500">加载调整申请记录中...</p>
        </div>
      </div>

      <!-- 无数据状态 -->
      <div v-else-if="historyRecords.length === 0" class="text-center py-8">
        <el-empty description="暂无课程调整申请记录"></el-empty>
      </div>

      <!-- 历史记录表格 -->
      <el-table
          v-else
          :data="historyRecords"
          border
          stripe
          :header-cell-style="{background: '#f5f7fa'}"
          max-height="500"
          class="transition-all duration-300"
      >
        <el-table-column prop="courseName" label="课程名称" min-width="180"></el-table-column>
        <el-table-column label="调整类型" min-width="120">
          <template #default="scope">
            {{ getAdjustmentReasonText(scope.row.adjustmentReason) }}
          </template>
        </el-table-column>
        <el-table-column label="调整范围" min-width="120">
          <template #default="scope">
            {{ scope.row.adjustmentRange === '1' ? '临时调整' : '整个周期调整' }}
          </template>
        </el-table-column>
        <el-table-column label="原时间" min-width="160">
          <template #default="scope">
            {{ getWeekDay(scope.row.originalWeekDay) }} {{ scope.row.originalStartTime }}-{{ scope.row.originalEndTime }}
          </template>
        </el-table-column>
        <el-table-column label="调整后时间" min-width="160">
          <template #default="scope">
            {{ scope.row.newWeekDay ? getWeekDay(scope.row.newWeekDay) + ' ' + scope.row.newStartTime + '-' + scope.row.newEndTime : '无' }}
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="申请日期" min-width="120">
          <template #default="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="approvalStatus" label="审批状态" min-width="120">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.approvalStatus)">
              {{ getApprovalStatusText(scope.row.approvalStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="100">
          <template #default="scope">
            <el-button
                link
                type="primary"
                size="small"
                @click="viewHistoryDetail(scope.row)"
                class="hover:text-primary transition-colors"
            >
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElEmpty, ElIcon } from 'element-plus';
import { Loading } from '@element-plus/icons-vue';
import {
  getCourseScheduleDetailsByTeacherId00,
  selectAdjustmentRecordByOriginalTeacherId
} from "@/api/course/availability";
import { useRouter } from 'vue-router';
import { getClassroom } from "@/api/classroom/classroom"

// 路由相关
const router = useRouter();

// 课程列表数据
const courseList = ref([]);
// 筛选后的课程列表
const filteredCourseList = ref([]);
// 表格加载状态
const tableLoading = ref(false);

// 历史调课记录相关
const historyRecords = ref([]);
const historyLoading = ref(false);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 搜索和筛选条件
const searchKeyword = ref('');
const selectedSemester = ref('');

// 调整原因映射（备用，如果字典数据不可用）
const adjustmentReasons = {
  1: { label: '教师请假' },
  2: { label: '教师培训' },
  3: { label: '教室冲突' },
  4: { label: '考试安排' },
  5: { label: '其他原因' }
};

// 加载课程列表 - 修复版本
const loadCourses = async () => {
  tableLoading.value = true;
  try {
    const response = await getCourseScheduleDetailsByTeacherId00();
    console.log('课程接口返回完整数据:', response);

    let courseData = [];
    if (response && Array.isArray(response)) {
      courseData = response;
    } else if (response && response.data && Array.isArray(response.data)) {
      courseData = response.data;
    } else if (response && Array.isArray(response.rows)) {
      courseData = response.rows;
    }

    if (courseData.length > 0) {
      const formattedCourses = [];
      const classroomCache = new Map();

      for (const item of courseData) {
        if (!item.courseScheduleDetails || !item.classScheduleDetailedList) {
          console.warn('跳过无效的课程数据结构:', item);
          continue;
        }

        const baseInfo = item.courseScheduleDetails;
        const scheduleDetails = item.classScheduleDetailedList;

        const academicYear = baseInfo.academicYear || baseInfo.grade;
        const academicYearText = academicYear
            ? `${academicYear}-${academicYear + 1}学年`
            : '未知学年';

        const semesterText = baseInfo.semester === 1 ? '第一学期' : '第二学期';

        const currentEnrollment = Number(baseInfo.currentEnrollment) || 0;
        const maxCapacity = Number(baseInfo.maxCapacity) || 0;
        const enrollmentRate = maxCapacity > 0
            ? Math.round((currentEnrollment / maxCapacity) * 100)
            : 0;

        // 获取教室ID
        const classroomId = baseInfo.classroom;
        console.log('获取到教室ID:', classroomId);

        // 获取教室名称 - 直接使用正确的字段名
        let classroomName = '未知教室';

        if (classroomId && classroomId !== '未知教室') {
          try {
            if (classroomCache.has(classroomId)) {
              classroomName = classroomCache.get(classroomId);
            } else {
              console.log(`调用getClassroom接口，教室ID: ${classroomId}`);
              const classroomResponse = await getClassroom(classroomId);
              console.log('教室接口完整返回:', classroomResponse);

              // 直接使用正确的字段名：classRoomName
              if (classroomResponse && classroomResponse.data && classroomResponse.data.classRoomName) {
                classroomName = classroomResponse.data.classRoomName;
                console.log(`获取到教室名称: ${classroomName}`);
                classroomCache.set(classroomId, classroomName);
              } else {
                console.warn('未找到classRoomName字段');
                classroomName = '未知教室';
                classroomCache.set(classroomId, classroomName);
              }
            }
          } catch (error) {
            console.error('获取教室信息失败:', error);
            classroomName = '未知教室';
            classroomCache.set(classroomId, classroomName);
          }
        }

        // 为每个上课时间段创建课程条目
        scheduleDetails.forEach(detail => {
          formattedCourses.push({
            courseScheduleDetails: baseInfo,
            classScheduleDetailedList: scheduleDetails,
            currentDetail: detail,

            id: baseInfo.id,
            courseId: baseInfo.courseId || '',
            courseName: (baseInfo.className || '').split('-')[0] || '未知课程',
            className: baseInfo.className || '未知班级',
            academicYear: academicYearText,
            semesterText,
            semesterNum: baseInfo.semester || 0,
            weekDay: detail.weekDay,
            startTime: detail.startTime || '未知',
            endTime: detail.endTime || '未知',
            weekType: detail.weekType,
            classroom: classroomName,
            currentEnrollment,
            maxCapacity,
            enrollmentRate,
            department: baseInfo.department || '未知学院',
            status: baseInfo.status || 1,
            lessonCount: detail.lessonCount || 0,
            scheduleId: detail.id || ''
          });
        });
      }

      courseList.value = formattedCourses;
      total.value = formattedCourses.length;
      handleFilterChange();
      console.log('格式化后的课程数据:', formattedCourses);
    } else {
      ElMessage.info('暂无课程数据');
      courseList.value = [];
      filteredCourseList.value = [];
      total.value = 0;
    }
  } catch (error) {
    ElMessage.error('获取课程列表时发生错误');
    console.error('课程列表接口异常:', error);
  } finally {
    tableLoading.value = false;
  }
};

// 加载课程调整申请记录
const loadAdjustmentRecords = async () => {
  historyLoading.value = true;
  try {
    console.log('开始加载课程调整申请记录');
    // 不传递任何参数，后端通过当前登录用户获取教师ID
    const response = await selectAdjustmentRecordByOriginalTeacherId();

    // 适配不同的接口返回格式
    let records = response.data || response.rows || response || [];

    // 确保records是数组
    if (!Array.isArray(records)) {
      records = [];
    }

    // 格式化记录数据，适配表格展示
    historyRecords.value = records.map(record => ({
      ...record,
      courseName: record.originalClassName || '未知课程'
    }));

    console.log('成功加载课程调整申请记录，共', historyRecords.value.length, '条');
  } catch (error) {
    console.error('加载课程调整申请记录失败:', error);
    ElMessage.error(`加载课程调整申请记录失败: ${error.message || '未知错误'}`);
    historyRecords.value = [];
  } finally {
    historyLoading.value = false;
  }
};

// 页面加载时直接加载课程和调整记录
onMounted(() => {
  loadCourses();
  loadAdjustmentRecords();
});

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  handleFilterChange();
};

// 处理筛选变化
const handleFilterChange = () => {
  let result = [...courseList.value];

  // 搜索筛选
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase();
    result = result.filter(course =>
        course.courseName.toLowerCase().includes(keyword) ||
        (course.courseId && course.courseId.toLowerCase().includes(keyword)) ||
        course.className.toLowerCase().includes(keyword) ||
        (course.department && course.department.toLowerCase().includes(keyword))
    );
  }

  // 学期筛选
  if (selectedSemester.value) {
    const [year, semester] = selectedSemester.value.split('-');
    result = result.filter(course => {
      // 匹配学年
      const matchesYear = course.academicYear.includes(year);
      // 匹配学期
      const matchesSemester = semester === '1'
          ? course.semesterText.includes('第一')
          : course.semesterText.includes('第二');
      return matchesYear && matchesSemester;
    });
  }

  filteredCourseList.value = result;
  total.value = result.length;
};

// 处理分页事件
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
};

// 显示课程详情
const showCourseDetail = (course) => {
  console.log('课程详情:', course);
  ElMessage.info('课程详情功能待实现');
};

// 选择课程
const selectCourse = (course) => {
  // 组装需要传递的数据
  const dataToPass = {
    courseScheduleDetails: course.courseScheduleDetails,
    classScheduleDetailedList: [course.currentDetail]
  };
  router.push({
    path: '/courseAdjustmentRecord',
    query: {
      courseData: JSON.stringify(dataToPass)
    }
  });
};

// 查看历史记录详情
const viewHistoryDetail = (record) => {
  console.log('课程调整记录详情:', record);
  ElMessage.info('记录详情功能待实现');
};

// 转换星期几
const getWeekDay = (day) => {
  const weekdays = ['', '周一', '周二', '周三', '周四', '周五', '周六', '周日'];
  const dayNum = parseInt(day, 10);
  return weekdays[dayNum] || '未知';
};

// 获取调整原因文本
const getAdjustmentReasonText = (reason) => {
  // 这里可以使用字典数据，如果没有则使用备用映射
  return adjustmentReasons[reason]?.label || `原因${reason}`;
};

// 获取审批状态文本
const getApprovalStatusText = (status) => {
  switch (status) {
    case '0':
      return '待审批';
    case '1':
      return '已通过';
    case '2':
      return '已拒绝';
    default:
      return '未知状态';
  }
};

// 状态标签样式映射
const getStatusTagType = (status) => {
  switch (status) {
    case '0':
      return 'info';
    case '1':
      return 'success';
    case '2':
      return 'danger';
    default:
      return 'warning';
  }
};

// 格式化日期显示
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  }).replace(/\//g, '-');
};
</script>

<style scoped lang="scss">
.app-container {
  padding: 20px;
}

::v-deep .el-card__body {
  padding: 20px;
}

::v-deep .el-form-item {
  margin-bottom: 16px;
}

// 表格样式优化
::v-deep .el-table__cell {
  padding: 12px 0;
}

// 进度条样式调整
::v-deep .el-progress {
  display: inline-block;
}

// 历史记录区域样式
::v-deep .el-card + .el-card {
  margin-top: 20px;
}

// 响应式调整
@media (max-width: 768px) {
  .app-container {
    padding: 10px;
  }

  ::v-deep .el-card__body {
    padding: 15px;
  }
}

// 加载状态样式
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
}

// 标题图标样式
.text-primary {
  color: #409eff;
}

// 卡片悬停效果
::v-deep .el-card {
  transition: all 0.3s ease;
}

::v-deep .el-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

// 表格行悬停效果
::v-deep .el-table__row {
  transition: background-color 0.2s ease;
}

// 按钮样式调整
::v-deep .el-button--link {
  padding: 0;
  height: auto;
}
</style>